from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
import pandas as pd


# 导入数据
data = pd.read_csv(r"C:\Users\Lenovo\Desktop\Insightful & Vast USA Statistics\中位数填补_PCA降维后的数据.csv")

# 划分特征与标签
y = data.loc[:,data.columns == 'debt']
X = data.iloc[:,data.columns != 'debt']

# 划分训练集、测试集
Xtrain,Xtest,Ytrain,Ytest = train_test_split(X,y,test_size = 0.3,random_state = 420)


# 实例化各个模型
Ridge_model = Ridge()

# 训练模型
Ridge_model = Ridge_model.fit(Xtrain, Ytrain)


# 得出模型
print ( "岭回归权重系数为：\n" , Ridge_model.coef_ )
print ( "岭回归偏置为： \n" , Ridge_model.intercept_ )

# 模型评估
y_predict = Ridge_model.predict (Xtest)
print ( "预测debt：\n" , y_predict )
error = mean_squared_error (Ytest, y_predict )
print ( "岭回归均方误差为：\n" , error )
y_predict = pd.DataFrame ( y_predict )

# 导出结果
y_predict.to_csv(r"C:\Users\Lenovo\Desktop\Insightful & Vast USA Statistics\微观模型岭回归预测结果.csv")